#!/bin/bash

SUDO="sudo "
if [[ $(id -u) -eq 0 ]]; then SUDO=""; fi

read -p "Enter nodejs version (default 20.6.1): " version </dev/tty
version=$(echo "$version" | tr -s '[:space:]')
if [[ "$version" == "" ]]; then version="20.6.1"; fi

$SUDO mkdir -p /opt/node/${version}

if [[ -x /opt/node/$version/bin/node ]]; then 
    read -p "node[${version}] is installed, reinstall it? (y/N) " reinstall </dev/tty
    reinstall=$(echo "$reinstall" | tr -s '[:space:]')
    if [[ "$reinstall" != [Yy] ]]; then exit 0; fi
fi
$SUDO rm -rf /opt/node/${version}/*

if [[ ! -f node-v${version}-linux-x64.tar.gz ]]; then
    wget https://registry.npmmirror.com/-/binary/node/v${version}/node-v${version}-linux-x64.tar.gz
fi
if [[ ! -f node-v${version}-linux-x64.tar.gz ]]; then echo "download failed."; exit -1; fi

$SUDO tar -zxvf node-v${version}-linux-x64.tar.gz -C /opt/node/${version} --strip-components=1
rm -f node-v${version}-linux-x64.tar.gz

echo -e "\nMake sure that the following content exists in the \$HOME/.bashrc"
echo -e "\texport NODE_HOME=/opt/node/${version}"
echo -e "\texport PATH=\$NODE_HOME/bin:\$PATH"
